import cv2 as cv
import custom

#reinhard色彩传递函数

#读取目标图像和参考图像
target_rgb=cv.imread("pic/a2.png")
reference_rgb=cv.imread("pic/a1.png")
#将目标图像和参考图像转换为lab图像
target_lab = cv.cvtColor(target_rgb,cv.COLOR_BGR2LAB)
reference_lab = cv.cvtColor(reference_rgb,cv.COLOR_BGR2LAB)

(mean_t, stddv_t) = cv.meanStdDev(target_lab)     #计算目标图像的均值和方差
(mean_r, stddv_r) = cv.meanStdDev(reference_lab)  #计算参考图像的均值和方差
# print(mean_t[0],stddv_t[0])
# print(mean_t[1],stddv_t[1])
# print(mean_t[2],stddv_t[2])
# print()
# print(mean_r[0],stddv_r[0])
# print(mean_r[1],stddv_r[1])
# print(mean_r[2],stddv_r[2])

#算法过程：目标图片的每一个像素值，减去目标图像均值然后乘上参考图片和目标图片标准差的比值，再加上参考图像均值
#（目-目均）*参标/目标 +参均
height,width,channel = target_lab.shape
for i in range(0,height):
    for j in range(0,width):
        for k in range(0,channel):
            t = target_lab[i,j,k]
            t = (t-mean_t[k])*(stddv_r[k]/stddv_t[k]) + mean_r[k]
            t = 0 if t<0 else t
            t = 255 if t>255 else t
            target_lab[i,j,k] = t

Reinhard = cv.cvtColor(target_lab,cv.COLOR_LAB2BGR) #再转回RGB图像
custom.showPicture("target",target_rgb)
custom.showPicture("reference",reference_rgb)
custom.showPicture("Reinhard",Reinhard)

cv.waitKey(0)
cv.destroyAllWindows()